package com.lry.future.demo2;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author JiangJie
 * @create 2020-11-23 13:56
 */
public class Executors3 {

    public static void main(String[] args) {
        ListenerFuture<String> future = submit(() -> {
            return "hello";
        });

        future.setListener(new Listener<String>() {
            @Override
            public void onSuccess(String value) {
                System.out.println(value);
            }

            @Override
            public void OnFailed(Throwable cause) {
                System.out.println(cause);
            }
        });


        System.out.println(future.get());
    }

    public static <T> ListenerFuture<T> submit(Callable<T> callable) {

        AtomicReference<T> result = new AtomicReference<T>();
        AtomicBoolean flag = new AtomicBoolean(false);

        ListenerFuture<T> future = new ListenerFuture<T>() {
            Listener<T> listener = null;
            //阻塞方法
            @Override
            public T get() {
                synchronized (result) {
                    try {
                        result.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return result.get();
            }

            @Override
            public boolean isDone() {
                return flag.get();
            }

            @Override
            public void setListener(Listener<T> listener) {
                this.listener = listener;
            }

            @Override
            public Listener<T> getListener() {
                return listener;
            }
        };

        //模拟执行任务耗时
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    T t = callable.run();
                    flag.set(true);
                    synchronized (result) {
                        result.set(t);
                        result.notify();
                    }
                    if (null != future.getListener()) {
                        future.getListener().onSuccess(t);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    if (null != future.getListener()) {
                        future.getListener().OnFailed(e.getCause());
                    }
                }
            }
        }).start();

        //future会异步返回，不会等任务执行完
        return future;
    }
}
